/**
 * 仓库主文件，用于创建仓库
 */

import { createStore, combineReducers, applyMiddleware } from "redux";
import { composeWithDevTools } from "@redux-devtools/extension";

// 引入拆分出去的 reducers
import counterReducer from "./reducers/counter-reducer";
import todosReducer from "./reducers/todos-reducer";

// 引入中间件
import aMidd from "./middlewares/a";
import bMidd from "./middlewares/b";
import loggerMidd from "./middlewares/logger";
import thunkMidd from "./middlewares/thunk";

// 模拟一个 combineReducers
function myCombineReducers(map: any) {
  // 返回一个 reducer 函数, 该函数称为  rootReducer
  return (state: any = {}, action: any) => {
    // 将 state 与 action 作为参数去调用 每一个子 reducer 函数，然后将他们的返回值赋值上即可。

    // 定义一份最终的 state 数据
    const result: any = {};
    // 遍历 map 对象，将他们的函数都执行一下
    for (let key in map) {
      result[key] = map[key](state[key], action);
    }

    // 最终将 result 作为最终state数据，给返回
    return result;
  };
}

// 合并 reducers
// const rootReducer = combineReducers({
//   count: counterReducer,
// });

// 合并 reducers 使用自己的 myCombineReducers
const rootReducer = myCombineReducers({
  count: counterReducer,
  todos: todosReducer,
});

/**
 * composeWithDevTools() 让 redux devtools 启用的
 *
 * 如果需要同时启用 devTools 与 中间件，则如下:
 * composeWithDevTools(applyMiddleware(aMidd))
 */
const store = createStore(
  rootReducer,
  composeWithDevTools(applyMiddleware(thunkMidd, aMidd, bMidd, loggerMidd))
);

// 导出 store
export default store;
